package leetcode.design;

import java.util.ArrayList;
import java.util.List;

class ProductOfNumbers {

    List<Integer> prefixProduct;

    public ProductOfNumbers() {
        prefixProduct = new ArrayList<>();
    }

    public void add(int num) {
        if (num != 0) {
            if (!prefixProduct.isEmpty()) {
                prefixProduct.add(prefixProduct.get(prefixProduct.size() - 1) * num);
            } else {
                prefixProduct.add(num);
            }
        } else {
            prefixProduct.clear();
        }
    }

    public int getProduct(int k) {
        if (k > prefixProduct.size()) {
            return 0;
        } else if (k == prefixProduct.size()) {
            return prefixProduct.get(prefixProduct.size() - 1);
        } else {
            return prefixProduct.get(prefixProduct.size() - 1) / prefixProduct.get(prefixProduct.size() - 1 - k);
        }
    }
}

/**
 * Your ProductOfNumbers object will be instantiated and called as such:
 * ProductOfNumbers obj = new ProductOfNumbers();
 * obj.add(num);
 * int param_2 = obj.getProduct(k);
 */

public class leetcode1352 {
    public static void main(String[] args) {
        ProductOfNumbers productOfNumbers = new ProductOfNumbers();
        productOfNumbers.add(3);        // [3]
        productOfNumbers.add(0);        // [3,0]
        productOfNumbers.add(2);        // [3,0,2]
        productOfNumbers.add(5);        // [3,0,2,5]
        productOfNumbers.add(4);        // [3,0,2,5,4]
        System.out.println(productOfNumbers.getProduct(2)); // 返回 20 。最后 2 个数字的乘积是 5 * 4 = 20
        System.out.println(productOfNumbers.getProduct(3)); // 返回 40 。最后 3 个数字的乘积是 2 * 5 * 4 = 40
        System.out.println(productOfNumbers.getProduct(4)); // 返回  0 。最后 4 个数字的乘积是 0 * 2 * 5 * 4 = 0
        productOfNumbers.add(8);        // [3,0,2,5,4,8]
        System.out.println(productOfNumbers.getProduct(2)); // 返回 32 。最后 2 个数字的乘积是 4 * 8 = 32
    }
}
